/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package network.packets;

import datamodel.Message;
import java.util.Vector;
import utils.StringUtils;
import utils.Utils;

/**
 *
 * @author Kvest
 */
public class MessagesArchiveResponce extends Packet
{
    private Vector messages;
    
    public MessagesArchiveResponce(byte[] data)
    {
        super(MESSAGES_ARCHIVE_RESPONCE, data);
    }
    
    public void parse(byte[] data)
    { 
        int offset = 2;
        
        //Количество сообщений
        byte[] buff4 = new byte[4];
        System.arraycopy(data, offset, buff4, 0, buff4.length);
        offset += buff4.length;
        int count = Utils.byteToInt(buff4);
                
        messages = new Vector(count);
        
        //Сообщения
        byte[] buff;
        for (int i = 0; i < count; ++i)
        {
            Message message = new Message();
            
            //Заголовок
            System.arraycopy(data, offset, buff4, 0, buff4.length);
            offset += buff4.length;
            buff = new byte[Utils.byteToInt(buff4)];
            System.arraycopy(data, offset, buff, 0, buff.length);
            offset += buff.length;
            message.setTitle(StringUtils.bytesToStr(buff));

            //Тело сообщения        
            System.arraycopy(data, offset, buff4, 0, buff4.length);
            offset += buff4.length;
            buff = new byte[Utils.byteToInt(buff4)];
            System.arraycopy(data, offset, buff, 0, buff.length);
            offset += buff.length;
            message.setText(StringUtils.bytesToStr(buff));
            
            messages.addElement(message);
        }
        
        buff4 = null;
        buff = null;
    }
    
    public int getCount()
    {
        return messages.size();
    }
    
    public Message getMessage(int index)
    {
        return (Message)messages.elementAt(index);
    }
    
    public void print()
    {
        System.out.println("MessagesArchiveResponce=["); 
        for (int i = 0 ; i < getCount(); ++i)
        {
            System.out.println(getMessage(i).getTitle() + " : " + getMessage(i).getText());
        }
        System.out.println("]");
    }
}
